#include "homewindow.h"
#include "ui_homewindow.h"
#include "common.h"

#include <QDateTime>
#include <QNetworkAccessManager>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

HomeWindow::HomeWindow(QWidget *parent) : QWidget(parent),
                                          ui(new Ui::HomeWindow)
{
    ui->setupUi(this);

    showTime(); // 打开主控页面时展示时间
    getWeather(DEFAULT_ADCODE); // 打开主控页面时获取天气

    // 绑定信号槽（如果遵守on_XXX_clicked命名规范，就无需再用下面的语句手动绑定）
    // 参考https://blog.csdn.net/sunxiaopengsun/article/details/78316638
    //connect(this->ui->button_weatherPage, &QPushButton::clicked, this, &HomeWindow::on_button_musicPage_clicked);
    //connect(this->ui->button_musicPage, &QPushButton::clicked, this, &HomeWindow::on_button_musicPage_clicked);
    //connect(this->ui->button_prev, &QPushButton::clicked, this, &HomeWindow::on_button_prev_clicked);
    //connect(this->ui->button_next, &QPushButton::clicked, this, &HomeWindow::on_button_next_clicked);
}

HomeWindow::~HomeWindow()
{
    delete ui;
}

// 展示时间函数
void HomeWindow::showTime()
{
    // 获取当前时间
    QDateTime dateTime = QDateTime::currentDateTime();

    // 转换时间格式
    QString time = dateTime.toString("yyyy-MM-dd") + '\n' + dateTime.toString("HH:mm:ss");

    ui->label_time->setText(time);

    // 定时器，每隔1s获取一次时间
    QTimer *timer = new QTimer();
    connect(timer, &QTimer::timeout, this, &HomeWindow::updateTime);
    timer->start(1000); // 1000ms
}

// 更新时间槽函数
void HomeWindow::updateTime()
{
    // 获取当前时间
    QDateTime dateTime = QDateTime::currentDateTime();

    // 转换时间格式
    QString time = dateTime.toString("yyyy-MM-dd") + '\n' + dateTime.toString("HH:mm:ss");

    ui->label_time->setText(time);
}

void HomeWindow::updatePlayState(bool playing)
{
    if (playing)
    {
        ui->button_playState->setStyleSheet("border-image: url(:/resources/media/pause.png);");
    }
    else
    {
        ui->button_playState->setStyleSheet("border-image: url(:/resources/media/start.png);");
    }
}

void HomeWindow::updatePlayInfo(QString titleText, QString timeText, qint64 position, qint64 duration)
{
    ui->label_musicTitle->setText(titleText);
    ui->label_musicTime->setText(timeText);

    ui->horizontalSlider->setMaximum(duration);
    ui->horizontalSlider->setSliderPosition(position);
}

// 更新天气槽函数
void HomeWindow::updateWeather(QNetworkReply *reply)
{
    try
    {
        QJsonDocument document = QJsonDocument::fromJson(reply->readAll());
        QJsonObject obj = document.object();

        // 通过json对象获取属性值
        QJsonArray dataArr = obj.value("data").toArray();
        int i = 0;
        QJsonObject dateObj = dataArr.at(i).toObject();

        QString getCity = obj.value("city").toString();
        ui->label_location->setText(getCity); // 城市

        QString getWeather = dateObj.value("wea").toString();
        ui->label_weather->setText(getWeather); // 天气

        QString getIcon = dateObj.value("wea_img").toString();
        QString styleSheet = QString(R"(border-image: url(:/resources/weather/%1.png);)").arg(getIcon);
        ui->button_weatherPage->setStyleSheet(styleSheet); // 天气图标

        QString getTodayTemperature = dateObj.value("tem").toString();
        ui->label_weather->setText(getTodayTemperature.append("℃")); // 今日平均气温
    } catch (exception) {
        qWarning() << "Received data is not in proper format!";
    }
}

// 跳转天气页面按钮槽函数
void HomeWindow::on_button_weatherPage_clicked()
{
    emit weatherSignal();
}

// 跳转音乐页面按钮槽函数
void HomeWindow::on_button_musicPage_clicked()
{
    emit musicSignal();
}

void HomeWindow::on_button_prev_clicked()
{
    emit musicPrevSignal();
}

void HomeWindow::on_button_next_clicked()
{
    emit musicNextSignal();
}

void HomeWindow::on_button_playState_clicked()
{
    emit musicToggleSignal();
}

// 获取天气数据函数
void HomeWindow::getWeather(qulonglong citycode)
{
    QNetworkAccessManager *manager = new QNetworkAccessManager();

    // 向天气api发起get请求
    // http://v1.yiketianqi.com/api?unescape=1&version=v91&appid=XXX&appsecret=XXX&ext=&cityid=XXX
    QString url = QString(WEATHER_URL).arg(APPID).arg(APPSECRET).arg(citycode);
    manager->get(QNetworkRequest(QUrl(url)));

    // manager发送结束信号，updateWeather接收
    connect(manager, &QNetworkAccessManager::finished, this, &HomeWindow::updateWeather);
}
